#!/usr/bin/env python3
"""
数据库迁移脚本：为conversations表添加voice_source字段
"""

import os
import sys
from sqlalchemy import text

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from app import app, db

def migrate_add_voice_source():
    """为conversations表添加voice_source字段"""
    with app.app_context():
        try:
            # 检查字段是否已存在
            result = db.session.execute(text("""
                SELECT column_name 
                FROM information_schema.columns 
                WHERE table_name = 'conversations' 
                AND column_name = 'voice_source'
            """))
            
            if result.fetchone():
                print("voice_source字段已存在，跳过迁移")
                return
            
            # 添加voice_source字段
            db.session.execute(text("""
                ALTER TABLE conversations 
                ADD COLUMN voice_source VARCHAR(32) DEFAULT 'david'
            """))
            
            db.session.commit()
            print("成功添加voice_source字段到conversations表")
            
        except Exception as e:
            db.session.rollback()
            print(f"迁移失败: {str(e)}")
            raise

if __name__ == "__main__":
    print("开始数据库迁移...")
    migrate_add_voice_source()
    print("数据库迁移完成！") 